package com.yixin.aps.common;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * @author wangxiaolei
 * @version 1.0, 2014/12/12
 * @since JDK1.6 modif by chen.gang use jdk1.8 java.util.Base64
 */
public class AESUtil {
	/*
	 * 加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式，key需要为16位。
	 */
	public static String defaultKey = "2017XCFetionAES_";

	private static byte[] ivByte = new byte[] { 112, (byte) 150, (byte) 156, 39, 8, (byte) 166, 46, (byte) 177, (byte) 153,
			(byte) 238, 13, 98, 79, 42, 40, 110 };

	// 加密
	public static String encrypt(String sSrc,String sKey) throws Exception {
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		byte[] raw = sKey.getBytes();
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		IvParameterSpec iv = new IvParameterSpec(ivByte);// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
		byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));
		// return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码。
		return Base64.getEncoder().encodeToString(encrypted);
	}

	// 解密
	public static String decrypt(String sSrc,String sKey) throws Exception {
		try {
			byte[] raw = sKey.getBytes("ASCII");
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			IvParameterSpec iv = new IvParameterSpec(ivByte);
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			// byte[] encrypted1 = new
			// BASE64Decoder().decodeBuffer(sSrc);//先用base64解密
			byte[] encrypted1 = Base64.getDecoder().decode(sSrc);
			byte[] original = cipher.doFinal(encrypted1);
			String originalString = new String(original, "UTF-8");
			return originalString;
		} catch (Exception ex) {
			return null;
		}
	}

	public static void main(String[] args) throws Exception {
		// 需要加密的字串
		/*String cSrc = "15910896929";
		System.err.println("加密前：" + cSrc);
		// 加密
		long lStart = System.currentTimeMillis();
		String enString = AESUtil.getInstance().encrypt(cSrc);
		System.err.println("加密后的字串是：" + enString);

		enString = java.net.URLEncoder.encode(enString, "utf-8");
		System.err.println("加密后URLEncoder.encode:" + enString);

		 long lUseTime = System.currentTimeMillis()-lStart;
		 System.err.println("加密耗时：" + lUseTime + "毫秒");

		////////////////// 一下是解密代码//////////////////////////////////////////////
		 String DeString=java.net.URLDecoder.decode(enString, "utf-8");
		System.err.println("解密前URLDncoder.decode：" + DeString);
		lStart = System.currentTimeMillis();
		DeString = AESUtil.getInstance().decrypt(DeString);
		System.err.println("解密后的字串是：" + DeString);
		lUseTime = System.currentTimeMillis()-lStart;
		System.err.println("解密耗时：" + lUseTime + "毫秒");*/
		
	}
}
